﻿using FastData.Caching;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;

namespace FastData
{
    public class UpdateQuery<T> : QueryBase<T> where T : new()
    {
        internal UpdateQuery(DataAccess data, T entity)
            : base(data)
        {
            if (entity != null)
            {
                foreach (PropertyInfo prop in typeof(T).GetDataProperties())
                {
                    if (prop.IsKey())
                    {
                        SetWhere(prop.Name, prop.GetValue(entity));
                    }
                    else
                    {
                        AddField(prop.Name, prop.GetValue(entity), true);
                    }
                }
            }
        }

        internal override string GetCommandText(ExecuteType type)
        {
            return Data.Provider.CreateUpdateText(this, type);
        }

        public UpdateQuery<T> Where(Expression<Func<T, bool>> expression)
        {
            SetWhere(expression);
            return this;
        }

        public UpdateQuery<T> Set<TKey>(Expression<Func<T, TKey>> expression, object value)
        {
            SetField(expression, value);
            return this;
        }

        public void ExecuteLazy()
        {
            Data.ExecuteLazy(this);
        }

        public int Execute()
        {
            return Data.ExecuteNonQuery(this);
        }

        internal override void ExecuteCompleted()
        {
            CacheProvider.Remove(new TableDependency(TableName));
        }
    }

}
